package com.baizhi.service.impl;

import com.baizhi.dao.BookDao;
import com.baizhi.Book;
import com.baizhi.service.BookService;
import com.baizhi.util.MyBatisUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

public class BookServiceImpl implements BookService {
    @Override
    public List<Book> selectOrderById(String column,int rownum) {
        SqlSession session = MyBatisUtils.openSession();
        List<Book> books=new ArrayList<>();
        try {
            BookDao mapper = session.getMapper(BookDao.class);
            books = mapper.selectOrderBy(column, rownum);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.close(session);
        }
        return books;
    }

    @Override
    public List<Book> selectOrderById(String column, String date,int rownum ) {
        SqlSession session = MyBatisUtils.openSession();
        List<Book> books=new ArrayList<>();
        try {
            BookDao mapper = session.getMapper(BookDao.class);
            books = mapper.selectOrder(column, rownum,date);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.close(session);
        }
        return books;
    }

    @Override
    public Book selectOne(int id) {
        SqlSession session = MyBatisUtils.openSession();
        Book books=new Book();
        try {
            BookDao mapper = session.getMapper(BookDao.class);
            books = mapper.selectOne(id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.close(session);
        }
        return books;
    }

    @Override
    public PageInfo<Book> PageBook(int pageIndex, int pageSize, int id) {
        SqlSession session = MyBatisUtils.openSession();
        List<Book> books=null;
        try {
            BookDao mapper = session.getMapper(BookDao.class);
            PageHelper.startPage(pageIndex,pageSize);
            books = mapper.PageBook(id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.close(session);
        }
        PageInfo<Book> page=new PageInfo<>(books);
        return page;
    }

    @Override
    public PageInfo<Book> pageFirst(int pageIndex, int pageSize, int id) {
        SqlSession session = MyBatisUtils.openSession();
        List<Book> books = null;
        try {
            BookDao mapper = session.getMapper(BookDao.class);
            PageHelper.startPage(pageIndex, pageSize);
            books = mapper.pageCateFirst(id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            MyBatisUtils.close(session);
        }
        PageInfo<Book> page = new PageInfo<>(books);
        return page;
    }
}
